package com.wman.sheep.mvp.presenter;

import android.content.Context;
import android.os.Bundle;
import android.view.Menu;

import com.wman.sheep.common.application.AbsAppContext;
import com.wman.sheep.mvp.view.IDelegate;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

/**
 * Created by Administrator on 2017/4/5.
 * Activity Presenter层的实现基类
 */

public abstract class ActivityPresenter<T extends IDelegate> extends AppCompatActivity {
    protected T mViewDelegate;
    public Context mContext;

    public ActivityPresenter() {
        try {
            mViewDelegate = getDelegateClass().newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException("create IDelegate error");
        } catch (IllegalAccessException e) {
            throw new RuntimeException("create IDelegate error");
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mViewDelegate.create(getLayoutInflater(), null, savedInstanceState);
        setContentView(mViewDelegate.getRootView());

        initToolbar();
        mViewDelegate.initWidget();

        this.mContext = this;

        bindEventListener();
        // 设置activity管理
        AbsAppContext.getActivityManager().addActivity(this);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (mViewDelegate == null) {
            try {
                mViewDelegate = getDelegateClass().newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException("create IDelegate error");
            } catch (IllegalAccessException e) {
                throw new RuntimeException("create IDelegate error");
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (mViewDelegate.getOptionsMenuId() != 0) {
            getMenuInflater().inflate(mViewDelegate.getOptionsMenuId(), menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    protected abstract void bindEventListener();

    protected void initToolbar() {
        Toolbar toolbar = mViewDelegate.getToolBar();
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mViewDelegate = null;
        AbsAppContext.getActivityManager().finishActivity(this);
        mContext = null;
    }

    protected abstract Class<T> getDelegateClass();
}
